package com.example.casesys.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.example.casesys.utils.FileUrlPatterns.*;

/**
 * 文件上传下载工具类
 * @author kongke
 * @date 2023/10/13
 */
@Component
public class FileUtil {

    /**
     * 文件上传
     * @return {@link Map}<{@link String}, {@link String}> url:上传成功的文件路径 fail：上传失败的原因
     */
    public Map<String, String> uploadFile(MultipartFile file) {
        HashMap<String, String> resMap = new HashMap<>();
        String url;
        String fileName;
        String cliName;
        if (file.getSize() / 51200 > 1024) {
            resMap.put("fail", "文件大小不能超过50MB");
            return resMap;
        } else {
            String random = String.valueOf(Date.parse(String.valueOf(new Date())));
            if (file.getOriginalFilename().endsWith(".doc") || file.getOriginalFilename().endsWith(".pdf") || file.getOriginalFilename().endsWith(".docx")) {
                //获取文件名
                fileName = file.getOriginalFilename();
                cliName = fileName;
                resMap.put("cliName",cliName);
                //获取文件的后缀名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                //重新生成文件名字
                fileName = random + "_" + UUID.randomUUID() + suffixName;
                resMap.put("serName",fileName);
                // 服务器中文件路径FILE_URL_LINUX
                File dest = new File(FILE_URL_LINUX + fileName);
//                判断文件夹是否存在
                if (!dest.getParentFile().exists()){
//                    不存在则创建
                    boolean mkdirs = dest.getParentFile().mkdirs();
                    if (!mkdirs) {
                        resMap.put("fail", "新建文件夹失败");
                        return resMap;
                    }
                }
                try {
                    file.transferTo(dest);
                } catch (IOException e) {
                    resMap.put("fail", "文件上传失败");
                    return resMap;
                }
                url = FILE_TO_DB_URL + fileName + "/" + cliName;
            } else {
                resMap.put("fail", "文件格式错误");
                return resMap;
            }
        }
        resMap.put("url", url);
        return resMap;
    }

    /**
     * 文件下载
     * @return {@link ResponseEntity}<{@link byte[]}>
     */
    public ResponseEntity<byte[]> downloadFile(String serName) {
        try {
            // 服务器上文件路径为FILE_URL_LINUX
            File file = new File(FILE_URL_LINUX + serName);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] body = new byte[inputStream.available()];
            inputStream.read(body);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment;filename=" + file.getName());
            HttpStatus statusCode = HttpStatus.OK;
            inputStream.close();
            return new ResponseEntity<>(body, headers, statusCode);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 删除服务器中的文件
     * @param filePath 文件存放路径
     * @return boolean
     */
    public boolean delFile(String filePath){
        File file = new File(filePath);
        if (file.isFile()){
            return file.delete();
        }
        return false;
    }

}
